package cn.yunyichina.provider.hisiface.sdk.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.apache.commons.lang.StringUtils;

public class MapUtils {

	/**
	 * 排序后组合字符串
	 * 
	 * @param data
	 * @return
	 */
	public static String coverMap2SignString(Map<String, String> data) {
		TreeMap<String, String> tree = new TreeMap<>();
		Iterator<Entry<String, String>> it = data.entrySet().iterator();
		while (it.hasNext()) {
			Entry<String, String> en = it.next();
			if ("sign".equals(en.getKey().trim())) {
				continue;
			}
			tree.put(en.getKey(), en.getValue());
		}

		it = tree.entrySet().iterator();
		StringBuffer sf = new StringBuffer();
		while (it.hasNext()) {
			Entry<String, String> en = it.next();
			sf.append(en.getValue());
		}

		return sf.toString();
	}
	
	/**
	 * 将Map中的数据转换成key1=value1&key2=value2的形式
	 *
	 * @param data 待拼接的Map数据
	 * @return 拼接好后的字符串
	 */
	public static String coverMap2String(Map<String, String> data) {
		StringBuffer sf = new StringBuffer();
		
		Iterator<Entry<String, String>> it = data.entrySet().iterator();
		while (it.hasNext()) {
			Entry<String, String> en = it.next();
			sf.append(en.getKey()).append("=").append(en.getValue());
			sf.append("&");
		}
		
		return sf.toString();
	}
	
	/**
	 * 将形如key=value&key=value的字符串转换为相应的Map对象
	 *
	 * @param res 形如key=value&key=value的字符串
	 * @return 转换后的Map对象
	 */
	public static Map<String, String> convertResultString2Map(String res) {
		Map<String, String> map = null;
		
		if (StringUtils.isNotBlank(res)) {
			String[] resArray = res.split("&");
			if (resArray.length > 0) {
				map = new HashMap<>(resArray.length);
				for (String arrayStr : resArray) {
					if (StringUtils.isBlank(arrayStr)) {
						continue;
					}
					
					int index = arrayStr.indexOf("=");
					if (-1 == index) {
						continue;
					}
					
					map.put(arrayStr.substring(0, index), arrayStr.substring(index + 1));
				}
			}
		}
		
		return map;
	}
}
